export function generateRandomString(length) {
    const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    let result = '';
    for (let i = 0; i < length; i++) {
        result += characters.charAt(Math.floor(Math.random() * characters.length));
    }
    return result;
}
//助教权限检查
async function checkTutorPermission(tutorId, courseCode) {
    const response = await fetch(`/check-tutor-permission?tutor_id=${tutorId}&course_code=${courseCode}`);
    const data = await response.json();
    return data.hasPermission;
}

// 生成唯一的章节编号
export async function generateUniqueChapterId() {
    let chapterId;
    let isUnique = false;
    while (!isUnique) {
        chapterId = generateRandomString(50);
        const checkResponse = await fetch(`/check-chapter-code?chapterId=${chapterId}`);
        const checkData = await checkResponse.json();
        if (!checkData.exists) {
            isUnique = true;
        }
    }
    return chapterId;
}

// 检查章节标题是否重复
export async function isChapterTitleDuplicate(courseCode, chapterTitle) {
    const response = await fetch(`/check-chapter-title?courseCode=${courseCode}&chapterTitle=${chapterTitle}`);
    const data = await response.json();
    return data.exists;
}

// 在checkRoleAndAddChapter函数中添加位置选择逻辑
export async function checkRoleAndAddChapter(courseCode, teacherUserId) {
    const urlParams = new URLSearchParams(window.location.search);
    const username = urlParams.get('username');
    const response = await fetch(`/user-info?username=${username}`);
    const data = await response.json();
    
    if (data.role === '教师') {
        if (data.user_id == teacherUserId) {
            // 获取当前章节列表
            const chaptersResponse = await fetch(`/get-chapters?courseCode=${courseCode}`);
            const chapters = await chaptersResponse.json();
            
            // 填充位置选择框
            const positionSelect = document.getElementById('chapterPosition');
            positionSelect.innerHTML = '';
            const maxOrder = chapters.length > 0 ? 
                Math.max(...chapters.map(c => c.chapter_order)) : -1;
            
            // 添加选项
            for (let i = 0; i <= maxOrder + 1; i++) {
                const option = document.createElement('option');
                option.value = i;
                option.textContent = `第${i + 1}章`;
                positionSelect.appendChild(option);
            }
            
            document.getElementById('courseCodeForChapter').value = courseCode;
            document.getElementById('addChapterModal').style.display = 'block';
        } else {
            alert('你无法对不属于你的课程进行该操作');
        }
    } else if(data.role === '助教' && await checkTutorPermission(data.user_id, courseCode)){
        // 同上逻辑
        const chaptersResponse = await fetch(`/get-chapters?courseCode=${courseCode}`);
        const chapters = await chaptersResponse.json();
        
        const positionSelect = document.getElementById('chapterPosition');
        positionSelect.innerHTML = '';
        const maxOrder = chapters.length > 0 ? 
            Math.max(...chapters.map(c => c.chapter_order)) : -1;
        
        for (let i = 0; i <= maxOrder + 1; i++) {
            const option = document.createElement('option');
            option.value = i;
            option.textContent = `第${i + 1}章`;
            positionSelect.appendChild(option);
        }
        
        document.getElementById('courseCodeForChapter').value = courseCode;
        document.getElementById('addChapterModal').style.display = 'block';
    } else if(data.role === '学生' || data.role === '助教'){
        alert('你无法对不属于你的课程进行该操作');
    }

}

// 修改addNewChapter函数以包含章节位置
export async function addNewChapter() {
    const chapterTitle = document.getElementById('chapterTitle').value;
    const chapterContent = document.getElementById('chapterContent').value;
    const courseCode = document.getElementById('courseCodeForChapter').value;
    const chapterOrder = document.getElementById('chapterPosition').value;

    if (!chapterTitle || !chapterContent) {
        alert('章节信息不合法');
        return;
    }
    if(chapterTitle.length>25){
        alert('章节名称不能超过25个字符');
        return;
    }
       if(chapterContent.length>100){
        alert('章节内容不能超过100个字符');
        return;
    }

    if (await isChapterTitleDuplicate(courseCode, chapterTitle)) {
        alert('章节标题已存在');
        return;
    }

    const chapterId = await generateUniqueChapterId();

    const response = await fetch('/add-chapter', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            chapter_id: chapterId,
            chapter_title: chapterTitle,
            chapter_content: chapterContent,
            course_code: courseCode,
            chapter_order: chapterOrder
        })
    });
    const result = await response.json();
    alert(result.message);
    closeAddChapterModal();
    // 刷新页面或更新UI
    window.location.reload();
}

// 关闭新增章节模态框
export function closeAddChapterModal() {
    document.getElementById('addChapterModal').style.display = 'none';
}

// 检查角色并删除章节
export async function checkRoleAndDeleteChapter(courseCode, teacherUserId) {
    const urlParams = new URLSearchParams(window.location.search);
    const username = urlParams.get('username');
    const response = await fetch(`/user-info?username=${username}`);
    const data = await response.json();
    if (data.role === '教师') {
        if (data.user_id == teacherUserId) {
            const chaptersResponse = await fetch(`/get-chapters?courseCode=${courseCode}`);
            const chapters = await chaptersResponse.json();
            if (chapters.length === 0) {
                alert('该课程暂无章节，无法删除');
                return;
            }
            // 填充选择框
            const deleteChapterSelect = document.getElementById('deleteChapterSelect');
            deleteChapterSelect.innerHTML = '';
            chapters.forEach(chapter => {
                const option = document.createElement('option');
                option.value = chapter.chapter_id;
                option.textContent = `第${chapter.chapter_order + 1}章 ${chapter.chapter_title}`;
                deleteChapterSelect.appendChild(option);
            });
            document.getElementById('deleteChapterModal').style.display = 'block';
        } else {
            alert('你无法对不属于你的课程进行该操作');
        }
    } else if(data.role === '助教' && await checkTutorPermission(data.user_id, courseCode)){
            const chaptersResponse = await fetch(`/get-chapters?courseCode=${courseCode}`);
            const chapters = await chaptersResponse.json();
            if (chapters.length === 0) {
                alert('该课程暂无章节，无法删除');
                return;
            }
            // 填充选择框
            const deleteChapterSelect = document.getElementById('deleteChapterSelect');
            deleteChapterSelect.innerHTML = '';
            chapters.forEach(chapter => {
                const option = document.createElement('option');
                option.value = chapter.chapter_id;
                option.textContent = chapter.chapter_title;
                deleteChapterSelect.appendChild(option);
            });
            document.getElementById('deleteChapterModal').style.display = 'block';
        }
}

// 关闭删除章节模态框
export function closeDeleteChapterModal() {
    document.getElementById('deleteChapterModal').style.display = 'none';
}

// 删除章节
export async function deleteChapter() {
    const deleteChapterSelect = document.getElementById('deleteChapterSelect');
    const chapterId = deleteChapterSelect.value;
    if (!chapterId) {
        alert('请选择要删除的章节');
        return;
    }

    const response = await fetch(`/delete-chapter?chapterId=${chapterId}`, {
        method: 'DELETE'
    });
    const result = await response.json();
    alert(result.message);
    closeDeleteChapterModal();
}

// 打开查看章节模态框
export async function openViewChaptersModal(courseCode) {
    const response = await fetch(`/get-chapters?courseCode=${courseCode}`);
    const chapters = await response.json();
    const chapterList = document.getElementById('chapterList');
    chapterList.innerHTML = '';
    if (chapters.length === 0) {
        chapterList.innerHTML = '<p class="no-content-message">暂无章节</p>';
    }
    chapters.forEach(chapter => {
        const chapterBox = document.createElement('div');
        chapterBox.classList.add('course-box');
        chapterBox.innerHTML = `
    <div class="chapter-container">
        <div class="chapter-header">
            <span class="chapter-badge">第${chapter.chapter_order + 1}章</span>
            <h3 class="chapter-title">${chapter.chapter_title}</h3>
        </div>
        
        <div class="chapter-content">
            <div class="content-header">
                <i class="fas fa-align-left content-icon"></i>
                <h4 class="content-title">章节内容</h4>
            </div>
            <div class="content-text">${chapter.chapter_content}</div>
        </div>
    </div>
`;
        chapterList.appendChild(chapterBox);
    });
    document.getElementById('viewChaptersModal').style.display = 'block';
}

// 关闭查看章节模态框
export function closeViewChaptersModal() {
    document.getElementById('viewChaptersModal').style.display = 'none';
}
    